package gecko.x;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 基本数据类型转换
 *
 * @author 陈永佳 (yoojiachen@gmail.com)
 */
public class CastX {

    private CastX() {
    }

    public static int toInt(Object value) {
        if (value instanceof Integer) {
            return ((Integer) value);
        } else if (value instanceof Long) {
            return ((Long) value).intValue();
        } else if (value instanceof Number) {
            return ((Number) value).intValue();
        } else {
            return Integer.parseInt(String.valueOf(value));
        }
    }

    public static long toLong(Object value) {
        if (value instanceof Integer) {
            return ((Integer) value).longValue();
        } else if (value instanceof Long) {
            return (Long) value;
        } else if (value instanceof Number) {
            return ((Number) value).longValue();
        } else {
            return Long.parseLong(String.valueOf(value));
        }
    }

    public static double toDouble(Object value) {
        if (value instanceof Double) {
            return (Double) value;
        } else if (value instanceof Float) {
            return ((Float) value).doubleValue();
        } else if (value instanceof Number) {
            return ((Number) value).longValue();
        } else {
            return Double.parseDouble(String.valueOf(value));
        }
    }

    public static boolean toBoolean(Object value) {
        if (value instanceof Boolean) {
            return (Boolean) value;
        } else if (value instanceof Number) {
            return 0 != ((Number) value).intValue();
        } else {
            return Boolean.parseBoolean(String.valueOf(value));
        }
    }

    public static String toString(Object value) {
        if (value instanceof String) {
            return (String) value;
        } else {
            return String.valueOf(value);
        }
    }

    @SuppressWarnings("unchecked")
    public static Map<String, Object> toStrMap(Object value) {
        if (value instanceof Map) {
            final Map<Object, Object> map = (Map<Object, Object>) value;
            return map.entrySet().stream()
                    .collect(Collectors.toMap(
                            e -> String.valueOf(e.getKey()),
                            Map.Entry::getValue
                    ));
        } else {
            return Collections.emptyMap();
        }
    }

    @SuppressWarnings("unchecked")
    public static <T> List<T> getList(Object value, Function<Object, T> transformer) {
        if (value instanceof Collection) {
            final List<Object> list = (List<Object>) value;
            return list.stream().map(transformer).collect(Collectors.toList());
        } else {
            return Collections.emptyList();
        }
    }
}
